package linc.cool.workqueue;

import com.rabbitmq.client.*;
import linc.cool.utils.RabbitConstant;
import linc.cool.utils.RabbitUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author yqlin
 * @date 2022/3/3 3:45 下午
 * @description
 */
@Slf4j
public class SMSConsumer_2 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(RabbitConstant.QUEUE_SMS, false, false, false, null);
        // 如果不写basicQos(1)），则自动MQ会将所有请求平均发送给所有消费者
        // basicQos,MQ不再对消费者一次发送多个请求，而是消费者处理完一个消息后（确认后），在从队列中获取一个新的
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_SMS, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String jsonSMS = new String(body);
                log.info("接收信息:{}", jsonSMS);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.error("error: {}", e.getMessage(), e);
                }
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}
